<?php
/**
 * Created by Adon.
 * User: Adon
 * Date: 2017/8/21
 * Time: 9:58
 */

namespace app\models;

use Curl\Curl;
use Hejiang\Express\Exceptions\TrackingException;
use Hejiang\Express\Trackers\TrackerInterface;
use Hejiang\Express\Waybill;

class ExpressDetailForm extends Model
{
    public $express_no;
    public $express;
    public $store_id;


    public  $getSupportedExpresses = [
        '澳大利亚邮政' => 'auspost',
        'AAE' => 'aae',
        '安信达' => 'anxindakuaixi',
        '百世' => 'huitongkuaidi',
        '百福东方' => 'baifudongfang',
        'BHT' => 'bht',
        '邦送' => 'bangsongwuliu',
        '希伊艾斯（CCES）' => 'cces',
        '中国东方（COE）' => 'coe',
        '传喜' => 'chuanxiwuliu',
        '加拿大邮政' => 'canpost',
        '大田' => 'datianwuliu',
        '德邦' => 'debangwuliu',
        'DPEX' => 'dpex',
        'DHL' => 'dhl',
        'DHL国际' => 'dhlen',
        'DHL德国' => 'dhlde',
        'D速' => 'dsukuaidi',
        '递四方' => 'disifang',
        'EMS' => 'ems',
        'EMS英文' => 'emsen',
        'EMS国际' => 'emsguoji',
        'EMS国际英文' => 'emsinten',
        'Fedex英文' => 'fedex',
        'Fedex' => 'fedexcn',
        'Fedex美国' => 'fedexus',
        '飞康达' => 'feikangda',
        '飞快达' => 'feikuaida',
        '凡客如风达' => 'rufengda',
        '风行天下' => 'fengxingtianxia',
        '飞豹' => 'feibaokuaidi',
        '港中能达' => 'ganzhongnengda',
        '国通' => 'guotongkuaidi',
        '广东邮政' => 'guangdongyouzhengwuliu',
        'GLS' => 'gls',
        '共速达' => 'gongsuda',
        '汇通' => 'huitongkuaidi',
        '汇强' => 'huiqiangkuaidi',
        '华宇' => 'tiandihuayu',
        '恒路' => 'hengluwuliu',
        '华夏龙' => 'huaxialongwuliu',
        '海航天天' => 'tiantian',
        '海外环球' => 'haiwaihuanqiu',
        '河北建华' => 'hebeijianhua',
        '海盟' => 'haimengsudi',
        '华企' => 'huaqikuaiyun',
        '山东海红' => 'haihongwangsong',
        '佳吉' => 'jiajiwuliu',
        '佳怡' => 'jiayiwuliu',
        '加运美' => 'jiayunmeiwuliu',
        '京广' => 'jinguangsudikuaijian',
        '急先达' => 'jixianda',
        '晋越' => 'jinyuekuaidi',
        '捷特' => 'jietekuaidi',
        '金大' => 'jindawuliu',
        '嘉里大通' => 'jialidatong',
        '快捷' => 'kuaijiesudi',
        '康力' => 'kangliwuliu',
        '跨越' => 'kuayue',
        '联昊通' => 'lianhaowuliu',
        '龙邦' => 'longbanwuliu',
        '蓝镖' => 'lanbiaokuaidi',
        '乐捷递' => 'lejiedi',
        '联邦' => 'lianbangkuaidi',
        '联邦英文' => 'lianbangkuaidien',
        '立即送' => 'lijisong',
        '隆浪' => 'longlangkuaidi',
        '门对门' => 'menduimen',
        '美国' => 'meiguokuaidi',
        '明亮' => 'mingliangwuliu',
        'OCS' => 'ocs',
        'OnTrac' => 'ontrac',
        '全晨' => 'quanchenkuaidi',
        '全际通' => 'quanjitong',
        '全日通' => 'quanritongkuaidi',
        '全一' => 'quanyikuaidi',
        '全峰' => 'quanfengkuaidi',
        '七天连锁' => 'sevendays',
        '如风达' => 'rufengda',
        '国内邮件' => 'youzhengguonei',
        '国际邮件' => 'youzhengguoji',
        '申通' => 'shentong',
        '顺丰' => 'shunfeng',
        '顺丰（英文结果）' => 'shunfengen',
        '三态' => 'santaisudi',
        '盛辉' => 'shenghuiwuliu',
        '速尔' => 'suer',
        '盛丰' => 'shengfengwuliu',
        '上大' => 'shangda',
        '三态' => 'santaisudi',
        '山东海红' => 'haihongwangsong',
        '赛澳递' => 'saiaodi',
        '山西红马甲' => 'sxhongmajia',
        '圣安' => 'shenganwuliu',
        '穗佳' => 'suijiawuliu',
        '天地华宇' => 'tiandihuayu',
        '天天' => 'tiantian',
        'TNT（中文结果）' => 'tnt',
        'TNT（英文结果）' => 'tnten',
        '通和天下' => 'tonghetianxia',
        'UPS（中文结果）' => 'ups',
        'UPS（英文结果）' => 'upsen',
        '优速' => 'youshuwuliu',
        'USPS（中英文）' => 'usps',
        '万家' => 'wanjiawuliu',
        '万象' => 'wanxiangwuliu',
        '微特派' => 'weitepai',
        '新邦' => 'xinbangwuliu',
        '信丰' => 'xinfengwuliu',
        '新邦' => 'xinbangwuliu',
        '新蛋奥硕' => 'neweggozzo',
        '香港邮政' => 'hkpost',
        '圆通' => 'yuantong',
        '韵达' => 'yunda',
        '运通' => 'yuntongkuaidi',
        '远成' => 'yuanchengwuliu',
        '亚风' => 'yafengsudi',
        '一邦' => 'yibangwuliu',
        '优速' => 'youshuwuliu',
        '源伟丰' => 'yuanweifeng',
        '元智捷诚' => 'yuanzhijiecheng',
        '越丰' => 'yuefengwuliu',
        '源安达' => 'yuananda',
        '原飞航' => 'yuanfeihangwuliu',
        '忠信达' => 'zhongxinda',
        '芝麻开门' => 'zhimakaimen',
        '银捷' => 'yinjiesudi',
        '一统飞鸿' => 'yitongfeihong',
        '中通' => 'zhongtong',
        '宅急送' => 'zhaijisong',
        '中邮' => 'zhongyouwuliu',
        '忠信达' => 'zhongxinda',
        '中速快件' => 'zhongsukuaidi',
        '芝麻开门' => 'zhimakaimen',
        '郑州建华' => 'zhengzhoujianhua',
        '中天万运' => 'zhongtianwanyun',
        '邮政' => 'youzhengguonei',
        '邮政国际' => 'youzhengguoji',
    ];

    public $status_text = [
        1 => '?',
        2 => '运输中',
        3 => '已签收',
        4 => '问题件',
    ];

    public function rules()
    {
        return [
            [['express', 'express_no'], 'trim'],
            [['express_no', 'express', 'store_id'], 'required'],
        ];
    }

    public function search()
    {
        if (!$this->validate()) {
            return $this->errorResponse;
        }
        return $this->getData1();
    }


    function getData1() {
        $status_map = [
            -1 => '已揽件',
            0 => '已揽件',
            1 => '已发出',
            2 => '在途中',
            3 => '派件中',
            4 => '已签收',
            5 => '已自取',
            6 => '问题件',
            7 => '已退回',
            8 => '已退签',
        ];

        $post_data = array();
        $post_data["customer"] = '825144520798EBD9CA5EE7E934476B50';
        $key= 'yTBIJHZU5571' ;

        $param['com'] =  strtolower($this->getSupportedExpresses[$this->transExpressName($this->express)]);
        $param['num'] = $this->express_no;
        $post_data["param"] = json_encode($param);
        $url='http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $response = curl_exec($ch);
        if(!$response) {

            return [
                'code' => 1,
                'msg' => '未获取物流信息'
            ];
        }

        $response = json_decode($response,true);
        $list = $response['data'];
        foreach ($list as &$item) {
            $item['datetime'] = $item['time'];
            $item['detail'] = $item['context'];
            unset($item['time']);
            unset($item['desc']);
        }

        if (isset($status_map[$response['state']])) {
            $status_text = $status_map[$response['state']];
        } else {
            $status_text = '状态未知';
        }
        return [
            'code' => 0,
            'data' => [
                'list' => $list,
                'status' => $response['state'],
                'status_text' => $status_text,
            ],
        ];
    }


    /**
     * 快递鸟
     * @deprecated 使用新方法getData()
     */
    public function searchByKdniao()
    {
        $cache_key = md5(json_encode($this->attributes));
        $cache_time = 3600;
        $data = \Yii::$app->cache->get($cache_key);
        if ($data) {
            return $data;
        }
        $curl = new Curl();
        $curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
        $api = "http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";
        $store = Store::findOne($this->store_id);
        if (!$store || !$store->kdniao_mch_id || !$store->kdniao_api_key) {
            return [
                'code' => 1,
                'msg' => '后台尚未配置物流接口信息，获取物流信息'
            ];
        }
        $mch_id = $store->kdniao_mch_id;
        $api_key = $store->kdniao_api_key;
        $express_data = json_encode([
            'ShipperCode' => $this->getExpressCode($this->express, 'kdniao'),
            'LogisticCode' => $this->express_no,
        ], JSON_UNESCAPED_UNICODE);
        $data = [
            'RequestData' => urlencode($express_data),
            'EBusinessID' => $mch_id,
            'RequestType' => '1002',
            'DataSign' => base64_encode(md5($express_data . $api_key)),
            'DataType' => '2',
        ];
        $curl->post($api, $data);
        $res = $curl->response;
        $res = json_decode($res);
        if (!$res) {
            return [
                'code' => 1,
                'msg' => '获取物流信息失败：系统错误',
            ];
        }
        if ($res && $res->Success == false) {
            return [
                'code' => 1,
                'msg' => '获取物流信息失败：' . $res->Reason,
            ];
        }
        $status = [
            '1' => 1,//?
            '2' => 2,//在途中
            '3' => 3,//已签收
            '4' => 4,//问题件
        ];
        $list = [];
        foreach ($res->Traces as $item) {
            $list[] = (object)[
                'datetime' => $item->AcceptTime,
                'detail' => $item->AcceptStation,
            ];
        }
        $list = array_reverse($list);
        $data = [
            'code' => 0,
            'data' => [
                'status' => $status[$res->State],
                'status_text' => $this->status_text[$status[$res->State]],
                'list' => $list,
            ],
        ];
        if ($data['data']['status'] === null) {
            $data['data']['status'] = '';
        }
        if ($data['data']['status_text'] === null) {
            $data['data']['status_text'] = '获取失败';
        }
        \Yii::$app->cache->set($cache_key, $data, $cache_time);
        return $data;
    }

    /**
     * @deprecated
     */
    private function getExpressCode($express, $type)
    {
        $express_afters = [
            '快递',
            '快运',
            '物流',
            '速运',
        ];
        $express_name = Express::find()->orderBy('sort')->where([
            'name' => $express,
            'type' => $type,
        ])->one();
        if ($express_name) {
            return $express_name->code;
        }
        foreach ($express_afters as $after) {
            $express = str_replace($after, '', $express);
        }
        $express = Express::find()->orderBy('sort')->where([
            'AND',
            ['LIKE', 'name', $express,],
            ['type' => $type,]
        ])->one();
        if ($express) {
            return $express->code;
        }
        return '';
    }

    private function transExpressName($name)
    {
        if (!$name) {
            return false;
        }
        $append_list = [
            '快递',
            '快运',
            '物流',
            '速运',
            '速递',
        ];
        foreach ($append_list as $append) {
            $name = str_replace($append, '', $name);
        }

        $name_map_list = [
            '邮政快递包裹' => '邮政',
            '邮政包裹信件' => '邮政',
        ];
        if (isset($name_map_list[$name])) {
            $name = $name_map_list[$name];
        }
        return $name;
    }

    private function getData()
    {
        /**@var array $status_map 定义在 Hejiang\Express\Status */
        $status_map = [
            -1 => '已揽件',
            0 => '已揽件',
            1 => '已发出',
            2 => '在途中',
            3 => '派件中',
            4 => '已签收',
            5 => '已自取',
            6 => '问题件',
            7 => '已退回',
            8 => '已退签',
        ];

        /** @var Waybill $wb */
        $wb = \Yii::createObject([
            'class' => 'Hejiang\Express\Waybill',
            'id' => $this->express_no,
            'express' => $this->transExpressName($this->express),
        ]);

        $tracker_class_list = [
            'Hejiang\Express\Trackers\Kuaidi100',
            'Hejiang\Express\Trackers\Kuaidiniao',
            'Hejiang\Express\Trackers\Kuaidiwang',
        ];

        foreach ($tracker_class_list as $tracker_class) {
            /** @var TrackerInterface $tracker */
            $tracker = \Yii::createObject([
                'class' => $tracker_class,
            ]);
            try {
                $list = $wb->getTraces($tracker)->toArray();
                if (!is_array($list)) {
                    return [
                        'code' => 1,
                        'msg' => '物流信息查询失败。',
                    ];
                }
                foreach ($list as &$item) {
                    $item['datetime'] = $item['time'];
                    $item['detail'] = $item['desc'];
                    unset($item['time']);
                    unset($item['desc']);
                }
            } catch (TrackingException $ex) {
                return [
                    'code' => 1,
                    'msg' => $ex->getResponse(),
                ];
                continue;
            }
            if (isset($status_map[$wb->status])) {
                $status_text = $status_map[$wb->status];
            } else {
                $status_text = '状态未知';
            }
            return [
                'code' => 0,
                'data' => [
                    'list' => $list,
                    'status' => $wb->status,
                    'status_text' => $status_text,
                ],
            ];
        }
        return [
            'code' => 1,
            'msg' => '未查询到物流信息。',
        ];
    }
}
